<template>
  <view class="order-confirm-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <text class="title">确认订单</text>
    </view>
    
    <!-- 收货地址 -->
    <view class="address-section" @click="goToAddressList">
      <view class="address-content" v-if="selectedAddress">
        <view class="address-info">
          <view class="address-name-phone">
            <text class="name">{{selectedAddress.name}}</text>
            <text class="phone">{{selectedAddress.phone}}</text>
          </view>
          <view class="address-detail">
            <text>{{selectedAddress.city}} {{selectedAddress.department}} {{selectedAddress.houseNumber}}</text>
          </view>
        </view>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
      <view class="no-address" v-else>
        <text>请选择收货地址</text>
        <uni-icons type="right" size="20" color="#999"></uni-icons>
      </view>
    </view>
    
    <!-- 店铺信息 -->
    <view class="shop-section">
      <view class="shop-info">
        <image :src="shopInfo.imgUrl" mode="aspectFill"></image>
        <text class="shop-name">{{shopInfo.name}}</text>
      </view>
      
      <!-- 商品列表 -->
      <view class="product-list">
        <view class="product-item" v-for="(product) in productList" :key="product._id">
          <image :src="product.imgUrl" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{product.name}} {{product.weight || ''}}</text>
            <view class="product-price-count">
              <text class="price">¥{{product.price}}</text>
              <text class="count">x{{product.count}}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 配送费 -->
      <view class="delivery-section">
        <text>配送费</text>
        <text>¥{{shopInfo.expressPrice || 0}}</text>
      </view>
    </view>
    
    <!-- 订单备注 -->
    <view class="remark-section">
      <text>订单备注</text>
      <input type="text" placeholder="请输入备注信息" v-model="remark" />
    </view>
    
    <!-- 底部状态栏 -->
    <view class="footer">
      <view class="total-price">
        <text>实付金额：</text>
        <text class="price">¥{{totalPrice.toFixed(2)}}</text>
      </view>
      <view class="submit-btn" @click="submitOrder">
        <text>提交订单</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopInfo: {},
      productList: [],
      selectedAddress: null,
      addressList: [],
      remark: '',
      totalPrice: 0
    }
  },
  onLoad(options) {
    // 从本地存储获取购物车数据和店铺信息
    const cartData = uni.getStorageSync('cartData');
    const shopInfo = uni.getStorageSync('shopInfo');
    
    if (shopInfo) {
      this.shopInfo = JSON.parse(shopInfo);
    }
    
    // 获取地址列表
    this.loadAddressList();
    
    // 获取商品详情
    if (cartData) {
      const cartProducts = JSON.parse(cartData);
      
      uni.request({
        url: 'http://localhost:3000/products-all',
        success: (res) => {
          if (res.statusCode === 200) {
            const products = res.data;
            
            // 构建商品列表
            this.productList = [];
            let total = 0;
            
            for (const id in cartProducts) {
              const product = products.find(item => item._id === id);
              if (product) {
                const count = cartProducts[id];
                this.productList.push({
                  _id: product._id,
                  name: product.name,
                  imgUrl: product.imgUrl,
                  price: product.price,
                  weight: product.weight,
                  count: count
                });
                
                total += product.price * count;
              }
            }
            
            // 加上配送费
            if (this.shopInfo.expressPrice) {
              total += parseFloat(this.shopInfo.expressPrice);
            }
            
            this.totalPrice = total;
          }
        },
        fail: (err) => {
          console.error('获取商品数据失败:', err);
          uni.showToast({
            title: '获取商品数据失败',
            icon: 'none'
          });
        }
      });
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    loadAddressList() {
      // 首先尝试从本地存储获取地址列表
      const localAddressList = uni.getStorageSync('addressList');
      
      if (localAddressList) {
        this.addressList = JSON.parse(localAddressList);
        
        // 获取默认地址或第一个地址
        const defaultAddress = this.addressList.find(item => item.isDefault);
        if (defaultAddress) {
          this.selectedAddress = defaultAddress;
        } else if (this.addressList.length > 0) {
          this.selectedAddress = this.addressList[0];
        }
      } else {
        // 如果本地没有，则从服务器获取
        uni.request({
          url: 'http://localhost:3000/address',
          success: (res) => {
            if (res.statusCode === 200) {
              this.addressList = res.data;
              
              // 保存到本地存储
              uni.setStorageSync('addressList', JSON.stringify(this.addressList));
              
              // 获取默认地址或第一个地址
              const defaultAddress = this.addressList.find(item => item.isDefault);
              if (defaultAddress) {
                this.selectedAddress = defaultAddress;
              } else if (this.addressList.length > 0) {
                this.selectedAddress = this.addressList[0];
              }
            }
          },
          fail: (err) => {
            console.error('获取地址数据失败:', err);
            uni.showToast({
              title: '获取地址数据失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    goToAddressList() {
      // 保存当前地址列表到本地存储，以便地址列表页面使用
      uni.setStorageSync('addressList', JSON.stringify(this.addressList));
      
      uni.navigateTo({
        url: '/pages/me/address-list?from=order',
        events: {
          // 监听地址选择事件
          addressSelected: (address) => {
            this.selectedAddress = address;
          }
        }
      });
    },
    
    submitOrder() {
      if (!this.selectedAddress) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        });
        return;
      }
      
      if (this.productList.length === 0) {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
        return;
      }
      
      // 显示确认提示框
      uni.showModal({
        title: '请确认支付?',
        content: '请尽快完成支付，否则将被取消',
        cancelText: '取消订单',
        confirmText: '确认支付',
        success: (res) => {
          if (res.confirm) {
            // 生成订单数据
            const orderData = {
              _id: 'order_' + Date.now(),
              shopInfo: this.shopInfo,
              products: this.productList,
              address: this.selectedAddress,
              remark: this.remark,
              totalPrice: this.totalPrice,
              status: 'pending',
              createTime: new Date().toISOString()
            };
            
            // 保存订单数据到本地存储
            let orderList = uni.getStorageSync('orderList');
            if (orderList) {
              orderList = JSON.parse(orderList);
            } else {
              orderList = [];
            }
            
            orderList.unshift(orderData);
            uni.setStorageSync('orderList', JSON.stringify(orderList));
            
            // 跳转到支付页面
            uni.navigateTo({
              url: `/pages/order/payment?orderId=${orderData._id}`
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
/* 文本溢出省略号 mixin 定义 */
@mixin text-ellipsis($line: 1) {
  @if $line == 1 {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  } @else {
    display: -webkit-box;
    -webkit-line-clamp: $line;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.order-confirm-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 140rpx;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;

  .header {
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    background-color: #fff;
    position: sticky;
    top: 0;
    z-index: 10;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .back-btn {
      margin-right: 20rpx;
      padding: 10rpx;
    }
    
    .title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .address-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 8rpx;
      background: linear-gradient(to bottom, #0086ff, #00c6ff);
    }
    
    .address-content, .no-address {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    
    .address-info {
      flex: 1;
      padding-left: 20rpx;
      
      .address-name-phone {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        
        .name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-right: 30rpx;
        }
        
        .phone {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .address-detail {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
      }
    }
    
    .no-address {
      flex: 1;
      font-size: 30rpx;
      color: #666;
      padding: 20rpx 0;
    }
  }

  .shop-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    
    .shop-info {
      display: flex;
      align-items: center;
      padding: 25rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      image {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
        margin-right: 20rpx;
        border: 1rpx solid #f0f0f0;
      }
      
      .shop-name {
        font-size: 30rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .product-list {
      .product-item {
        display: flex;
        padding: 30rpx;
        position: relative;
        
        &:not(:last-child)::after {
          content: '';
          position: absolute;
          left: 30rpx;
          right: 30rpx;
          bottom: 0;
          height: 1rpx;
          background-color: #f5f5f5;
        }
        
        image {
          width: 140rpx;
          height: 140rpx;
          border-radius: 12rpx;
          margin-right: 25rpx;
          background-color: #f5f5f5;
        }
        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          
          .product-name {
            font-size: 30rpx;
            color: #333;
            line-height: 1.4;
            @include text-ellipsis(2);
          }
          
          .product-price-count {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            margin-top: 20rpx;
            
            .price {
              font-size: 32rpx;
              color: #ff4d4f;
              font-weight: 600;
              
              &::before {
                content: '¥';
                font-size: 24rpx;
              }
            }
            
            .count {
              font-size: 28rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .delivery-section {
      display: flex;
      justify-content: space-between;
      padding: 25rpx 30rpx;
      font-size: 28rpx;
      color: #666;
      border-top: 1rpx solid #f5f5f5;
      
      text:last-child {
        color: #333;
        font-weight: 500;
      }
    }
  }

  .remark-section {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
    display: flex;
    align-items: center;
    
    text {
      font-size: 28rpx;
      color: #666;
      margin-right: 30rpx;
      flex-shrink: 0;
    }
    
    input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      height: 40rpx;
      line-height: 40rpx;
      
      &::placeholder {
        color: #ccc;
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
    z-index: 10;
    
    .total-price {
      flex: 1;
      font-size: 28rpx;
      color: #666;
      
      .price {
        font-size: 36rpx;
        color: #ff4d4f;
        font-weight: 600;
        margin-left: 10rpx;
        
        &::before {
          content: '¥';
          font-size: 28rpx;
        }
      }
    }
    
    .submit-btn {
      background: linear-gradient(to right, #0086ff, #00c6ff);
      color: #fff;
      padding: 0 60rpx;
      height: 80rpx;
      line-height: 80rpx;
      border-radius: 40rpx;
      font-size: 30rpx;
      font-weight: 500;
      box-shadow: 0 4rpx 16rpx rgba(0, 134, 255, 0.3);
      transition: all 0.3s;
      
      &:active {
        opacity: 0.9;
        transform: scale(0.98);
      }
    }
  }
}
</style>